package org.jeecg.modules.online.desform.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtil;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.*;
import org.jeecg.modules.online.desform.entity.*;
import org.jeecg.modules.online.desform.service.*;
import org.jeecg.modules.online.desform.util.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Description: 表单设计
 * @Author: jeecg-boot
 * @Date: 2019-05-16
 * @Version: V1.0
 */
@RestController("designFormApiController")
@RequestMapping("/desform")
@Slf4j
public class DesignFormApiController {

    @Autowired
    private IDesignFormService designFormService;
    @Autowired
    private IDesignFormTempletService designFormTempletService;

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    @Lazy
    private RedisUtil redisUtil;

    @Autowired
    private IDesignFormUrlAuthService designFormUrlAuthService;

    @Autowired
    private IDesignFormAuthService designFormAuthService;
    @Autowired
    private IDesignFormRouteService designFormRouteService;
    @Autowired
    private IDesignFormDataService designFormDataService;

    @Value("${jeecg.desform.theme-color}")
    private String desformThemeColor;

    @Value("${jeecg.desform.upload-type}")
    private String desformUploadType;

    @GetMapping("/getQiniuUploadToken")
    public Result<?> getQiniuUploadToken() {
        return Result.ok(QiniuUtils.getUploadToken());
    }

    /**
     * 获取服务器地址
     *
     * @param request
     * @return
     */
    private String getBaseUrl(HttpServletRequest request) {
        //update-begin--Author:scott  Date:20200927 for：LOWCOD-905【微服务测试】用户、部门等接口无法获取数据问题--------
        String x_gateway_base_path = request.getHeader("X_GATEWAY_BASE_PATH");
        if(oConvertUtils.isNotEmpty(x_gateway_base_path)){
            log.info("x_gateway_base_path = "+ x_gateway_base_path);
            return  x_gateway_base_path;
        }
        //update-end--Author:scott  Date:20200927 for：LOWCOD-905【微服务测试】用户、部门等接口无法获取数据问题--------

        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();
        String contextPath = request.getContextPath();
        return scheme + "://" + serverName + ":" + serverPort + contextPath;
    }

    /**
     * 自定义表单设计器
     * 检验 Token
     */
    public ModelAndView doIndex(ModelAndView modelAndView, HttpServletRequest request) {
        try {
            TokenUtils.verifyToken(request, sysBaseAPI, redisUtil);

            modelAndView.addObject("baseURL", this.getBaseUrl(request));
            modelAndView.addObject("qiniuConfig", QiniuUtils.getConfig().toJSONString());
            modelAndView.addObject("themeColor", desformThemeColor);
            modelAndView.addObject("uploadType", desformUploadType);
            modelAndView.setViewName("desform/designForm");
        } catch (Exception e) {
            e.printStackTrace();
            modelAndView.addObject("message", e.getMessage());
            modelAndView.setViewName("desform/error");
        }
        return modelAndView;
    }

    @RequestMapping("/index")
    public ModelAndView desgForm(ModelAndView modelAndView, HttpServletRequest request) {
        return this.doIndex(modelAndView, request);
    }

    @RequestMapping("/index/{id}")
    public ModelAndView desgForm(@PathVariable("id") String id, @RequestParam("isTemplet") Boolean isTemplet, ModelAndView modelAndView, HttpServletRequest request) {
        if (!StringUtil.isEmpty(id)) {

            // 模板表设计页面
            if (isTemplet != null && isTemplet) {
                DesignFormTemplet designFormTemplet = designFormTempletService.getById(id);
                if (designFormTemplet != null) {
                    modelAndView.addObject("designJson", designFormTemplet.getTempletJson());
                }
            } else {
                DesignForm designForm = designFormService.getById(id);
                if (designForm != null) {
                    modelAndView.addObject("desform", designForm);
                    modelAndView.addObject("desformName", designForm.getDesformName());
                    modelAndView.addObject("designJson", designForm.getDesformDesignJson());
                }
            }
        }
        return this.doIndex(modelAndView, request);
    }

    /**
     * @param modelAndView
     * @param urlType
     * @param desformCode
     * @param dataId
     * @param onlineDataId
     * @param request
     * @return
     */
    private ModelAndView doFormView(ModelAndView modelAndView, String urlType, String desformCode, String dataId, String onlineDataId, HttpServletRequest request) {
        try {
            // 判断 token 有效性
            TokenUtils.verifyToken(request, sysBaseAPI, redisUtil);

            // 判断url是否有打开授权
            if (designFormUrlAuthService.urlIsPassed(desformCode, urlType)) {
                modelAndView.addObject("action", urlType);
                modelAndView.addObject("themeColor", desformThemeColor);
                modelAndView.addObject("uploadType", desformUploadType);
                modelAndView.addObject("baseURL", this.getBaseUrl(request));
                modelAndView.addObject("qiniuConfig", QiniuUtils.getConfig().toJSONString());

                if (CommonConstant.DESIGN_FORM_URL_TYPE_VIEW.equals(urlType)) {
                    modelAndView = designFormService.queryFormViewById(desformCode, dataId, onlineDataId, modelAndView);
                } else {
                    // 判断是否是从移动端发起的请求
                    boolean isMobile = BrowserUtils.isMobile(request);
                    // 如果是就判断是否配置了移动端视图，配置了就走移动端的视图，否则走默认视图
                    if (isMobile) {
                        modelAndView = designFormService.queryFormAutoViewByCode(desformCode, dataId, onlineDataId, modelAndView);
                    } else {
                        modelAndView = designFormService.queryFormViewByCode(desformCode, dataId, onlineDataId, modelAndView);
                    }
                }

                // 查询权限
                String token = request.getParameter("token");
                String username = JwtUtil.getUsername(token);
                JSONObject userInfo = designFormAuthService.getUserInfoByUsername(username);
                modelAndView.addObject("authUserInfoJson", userInfo.toJSONString());

                String taskId = request.getParameter("taskId");
                List<DesignFormAuth> desformAuths;
                if (StringUtil.isEmpty(taskId)) {
                    desformAuths = designFormAuthService.queryByCode(desformCode);
                } else {
                    desformAuths = designFormAuthService.queryByTaskId(desformCode, taskId);
                }
                modelAndView.addObject("authInfoJson", JSON.toJSONString(desformAuths));

                // 查询出有效的下一步路由地址
                DesignFormRoute desformRoute = designFormRouteService.getEffectiveRoute(desformCode);
                if (desformRoute != null) {
                    modelAndView.addObject("nextRouteConfig", JSON.toJSONString(desformRoute));
                }
                // 判断有没有携带 routeDataId，有就查询出数据并传递给前台
                String routeDataId = request.getParameter("routeDataId");
                if (StringUtil.isNotBlank(routeDataId)) {
                    DesignFormData routeData = designFormDataService.getById(routeDataId);
                    if (routeData != null) {
                        modelAndView.addObject("routeData", routeData.getDesformDataJson());
                    }
                }

                // 最后返回 model and view
                modelAndView.setViewName("desform/formGenerate");
                return modelAndView;
            } else {
                modelAndView.addObject("message", "无打开此链接的权限");
            }
        } catch (JeecgBootException e) {
            modelAndView.addObject("message", e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            modelAndView.addObject("message", e.getMessage());
        }
        modelAndView.setViewName("desform/error");
        return modelAndView;
    }

    /**
     * 表单编辑、修改
     */
    @RequestMapping("/view/{desformId}/{dataId}")
    public ModelAndView formView(@PathVariable("desformId") String desformId, @PathVariable("dataId") String dataId, ModelAndView modelAndView, HttpServletRequest request) {
        String urlType = CommonConstant.DESIGN_FORM_URL_TYPE_VIEW;
        return this.doFormView(modelAndView, urlType, desformId, dataId,null, request);
    }

    /**
     * 表单新增
     */
    @RequestMapping("/add/{desformCode}")
    public ModelAndView addDesformData(@PathVariable("desformCode") String desformCode, ModelAndView modelAndView, HttpServletRequest request) {
        String urlType = CommonConstant.DESIGN_FORM_URL_TYPE_ADD;
        return this.doFormView(modelAndView, urlType, desformCode, "add",null, request);
    }

    /**
     * 表单编辑修改
     */
    @RequestMapping("/edit/{desformCode}/{dataId}")
    public ModelAndView formEditByCode(@PathVariable("desformCode") String desformCode, @PathVariable("dataId") String dataId, ModelAndView modelAndView, HttpServletRequest request) {
        String urlType = CommonConstant.DESIGN_FORM_URL_TYPE_EDIT;
        return this.doFormView(modelAndView, urlType, desformCode, dataId,null, request);
    }

    //update-begin--Author:zhangdaihao  Date:20191003 for：实现表单的渲染，直接通过online dataid进行渲染，design_form_data无数据-------------------
    /**
     * 表单编辑修改
     */
    @RequestMapping("/edit/online/{desformCode}/{onlineDataId}")
    public ModelAndView formEditByCodeByOnline(@PathVariable("desformCode") String desformCode,@PathVariable("onlineDataId") String onlineDataId, ModelAndView modelAndView, HttpServletRequest request) {
        String urlType = CommonConstant.DESIGN_FORM_URL_TYPE_EDIT;
        return this.doFormView(modelAndView, urlType, desformCode, null,onlineDataId, request);
    }
    //update-end--Author:zhangdaihao  Date:20191003 for：实现表单的渲染，直接通过online dataid进行渲染，design_form_data无数据-------------------

    /**
     * 表单预览
     *  示例： desform/detail/cc_user_sjq/1252475006019010561
     */
    @RequestMapping("/detail/{desformCode}/{dataId}")
    public ModelAndView formDetail(@PathVariable("desformCode") String desformCode, @PathVariable("dataId") String dataId, ModelAndView modelAndView, HttpServletRequest request) {
        // 浏览页面只读模式
        modelAndView.addObject("isReadOnly", true);
        String urlType = CommonConstant.DESIGN_FORM_URL_TYPE_DETAIL;
        return this.doFormView(modelAndView, urlType, desformCode, dataId,null, request);
    }

    //update-begin--Author:zhangdaihao  Date:20191003 for：实现表单的渲染，直接通过online dataid进行渲染，design_form_data无数据-------------------
    /**
     * 表单预览
     */
    @RequestMapping("/detail/online/{desformCode}/{onlineDataId}")
    public ModelAndView formDetailByOnline(@PathVariable("desformCode") String desformCode, @PathVariable("onlineDataId") String onlineDataId, ModelAndView modelAndView, HttpServletRequest request) {
        // 浏览页面只读模式
        modelAndView.addObject("isReadOnly", true);
        String urlType = CommonConstant.DESIGN_FORM_URL_TYPE_DETAIL;
        return this.doFormView(modelAndView, urlType, desformCode, null,onlineDataId, request);
    }
    //update-end--Author:zhangdaihao  Date:20191003 for：实现表单的渲染，直接通过online dataid进行渲染，design_form_data无数据-------------------

    /**
     * 自定义接收URL：将数据抽取到新的表单
     * 【测试示例】
     * @param json
     * @param request
     * @return
     */
    @RequestMapping("/customUrlTest")
    public Result customUrlTest(@RequestBody JSONObject json, HttpServletRequest request) {
        boolean isPost = HttpMethod.POST.matches(request.getMethod());
        // post 为新增，put为修改，这里只对新增数据做处理
        if (isPost) {
            // 获取传递的 token
            String token = TokenUtils.getTokenByRequest(request);
            // 从传递进来的 formData 里抽取三个字段
            JSONObject formData = json.getJSONObject("desformDataJson");
            JSONObject staff = new JSONObject();
            staff.put("name", formData.getString("name"));
            staff.put("sex", formData.getString("sex"));
            staff.put("age", formData.getString("age"));
//            if(true){
//                throw new JeecgBootException("保存错误");
//            }
            // 通过 RESTful 风格的接口保存数据
            return RestDesformUtil.addOne("extract_test_staff", staff, token);
        } else {
            // 其他请求不做处理
//            if(true){
//                throw new JeecgBootException("修改错误");
//            }
            return Result.ok();
        }
    }

}
